package net.cyndeline.GUI.graphics

import javafx.scene.image.{WritableImage, ImageView, Image}
import net.cyndeline.misc.ResourceLoader
import javafx.geometry.Rectangle2D

/**
 * Used to load sprites from a sprite sheet into ImageViews of their own.
 * @param sheetPath The file path to the sprite sheet image file.
 * @param spriteWidth The width in pixels each sprite has.
 * @param spriteHeight The height in pixels each sprite has.
 */
class SpriteSheet(sheetPath: String, spriteWidth: Int, spriteHeight: Int) {
  private val sheet = new Image(ResourceLoader.load(sheetPath))
  private val pixelReader = sheet.getPixelReader

  /**
   * Reads a subsection of the loaded sprite sheet into its own image view.
   * @param row Which row of the sprite sheet the sprite lies on. The first row is 0.
   * @param column Which column of the sprite sheet the sprite lies on. The column row is 0.
   * @return An image view containing only the sprite, of the same width and height as stated in the constructor.
   */
  def readSprite(row: Int, column: Int): Image = {
    val xStart = row * spriteWidth
    val yStart = column * spriteHeight
    val sprite = new WritableImage(spriteWidth, spriteHeight)
    val spriteWriter = sprite.getPixelWriter
    var i = 0
    var j = 0

    while (i < xStart + spriteWidth) {
      while (j < yStart + spriteHeight) {
        val color = pixelReader.getColor(i, j)
        spriteWriter.setColor(i - xStart, j - yStart, color)
        j += 1
      }
      i += 1
    }
    sprite
  }


}
